import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { SystemDictDataItemType, SystemDictStateType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElButton,
  ElIcon,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import { View, EditPen, Delete, Plus, CirclePlus } from '@element-plus/icons-vue'
import { handleTrim } from '~/utils/util'
import ProSaasTable from '~/components/ProSaasTable'
import SearchForm from '~/components/ProForm/SearchForm'
import useVuexGetters from '~/hooks/useVuexGetters'
import SystemDictOptionsModal from './options'

export default defineComponent(function systemDict() {
  const store = useStore()
  // 初始值
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<SystemDictDataItemType>({})
  const state = reactive<SystemDictStateType>({
    modalVisible: false,
    type: 'read',
    record: {}
  })

  const systemDictState = useVuexGetters('systemDict', ['parentDictSelectList', 'parentDictEnum'])

  onMounted(() => {
    getSystemDictTreeAjax()
  })

  // methods
  // 上级字典
  const getSystemDictTreeAjax = () => {
    store.dispatch('systemDict/GetSystemDictTree', { code: 'DICT' }) // 上级字典
  }

  // 增改查 弹窗
  const handleChangeOptionsModal = (
    type: SystemDictStateType['type'],
    record?: SystemDictDataItemType
  ) => {
    state.modalVisible = !state.modalVisible
    state.record = record || {}
    state.type = type
    if (!state.modalVisible) {
      proSaasTableRef.value!?.toSearch() // 更新主列表
      getSystemDictTreeAjax() // 更新上级字典
    }
  }

  // 删除
  const handleOpenDeleteConfirm = (record?: SystemDictDataItemType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择至少一条数据' })
      return
    }
    let params = ''
    if (record?.id) {
      params = record?.id // 待删的id
    }
    ElMessageBox.confirm('确定将选择数据删除?', {
      buttonSize: 'small',
      type: 'warning',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        await store.dispatch('systemDict/PostSystemDictRemove', params).then((res) => {
          if (res?.code === 200) {
            proSaasTableRef.value!?.toSearch()
            getSystemDictTreeAjax() // 更新上级字典
            ElMessage({ type: 'success', message: '操作成功' })
          } else {
            ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
          }
        })
      })
      .catch(() => {})
  }

  const columns: TableColumnProps<SystemDictDataItemType>[] = [
    {
      label: '字典编号',
      prop: 'code',
      minWidth: 180,
      showOverflowTooltip: true
    },
    {
      label: '字典名称',
      prop: 'dictValue',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '上级字典',
      prop: 'parentId',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center',
      enumValues: systemDictState.parentDictEnum,
      render: (_, value) => {
        if (value === '0') {
          return <>{'顶级'}</>
        } else {
          return <>{value}</>
        }
      }
    },
    {
      label: '字典键值',
      prop: 'dictKey',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '字典排序',
      prop: 'sort',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '字典备注',
      prop: 'remark',
      minWidth: 180,
      showOverflowTooltip: true,
      align: 'center'
    },
    {
      label: '操作',
      prop: 'options',
      fixed: 'right',
      minWidth: 180,
      width: 324,
      align: 'center',
      render: ({ row }) => {
        return (
          <>
            <ElButton text type="primary" onClick={() => handleChangeOptionsModal('read', row)}>
              <ElIcon>
                <View />
              </ElIcon>
              &nbsp;查看
            </ElButton>
            <ElButton text type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
              <ElIcon>
                <EditPen />
              </ElIcon>
              &nbsp;编辑
            </ElButton>
            <ElButton text type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
              <ElIcon>
                <Delete />
              </ElIcon>
              &nbsp;删除
            </ElButton>
            {row.parentId === '0' && (
              <ElButton text type="primary" onClick={() => handleChangeOptionsModal('addSon', row)}>
                <ElIcon>
                  <CirclePlus />
                </ElIcon>
                &nbsp;新增子项
              </ElButton>
            )}
          </>
        )
      }
    }
  ]

  return () => (
    <ElCard>
      <SearchForm
        searchFormProps={{
          model: formValues
        }}
        searchformResponsiveCol={[
          <ElFormItem key="code" prop="code" label="字典编号：">
            <ElInput v-model={formValues.code} placeholder="请输入字典编号" clearable />
          </ElFormItem>,
          <ElFormItem key="dictValue" prop="dictValue" label="字典名称：">
            <ElInput v-model={formValues.dictValue} placeholder="请输入字典名称" clearable />
          </ElFormItem>,
          <ElFormItem key="remark" prop="remark" label="字典备注：">
            <ElInput v-model={formValues.remark} placeholder="请输入字典备注" clearable />
          </ElFormItem>
        ]}
        handleSearchList={proSaasTableRef.value?.toSearch}
      />
      <ProSaasTable<SystemDictDataItemType>
        ref={proSaasTableRef}
        columns={columns}
        rowKey="id"
        lazy
        treeProps={{ children: 'children', hasChildren: 'hasChildren' }}
        hasIndex
        hasSelection
        searchParams={{
          code: formValues.code && handleTrim(formValues.code),
          dictValue: formValues.dictValue && handleTrim(formValues.dictValue),
          remark: formValues.remark && handleTrim(formValues.remark)
        }}
        searchFormProps={{
          model: formValues
        }}
        dispatchType="systemDict/GetSystemDictList"
        dispatchTypeGetListKeys="data"
        headerTitle={
          <>
            <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
              <ElIcon>
                <Plus />
              </ElIcon>
              &nbsp; 新增
            </ElButton>
          </>
        }
      />
      {state.modalVisible && (
        <SystemDictOptionsModal
          visible={state.modalVisible}
          type={state.type}
          record={state.record}
          onCancel={() => handleChangeOptionsModal('read')}
        />
      )}
    </ElCard>
  )
})
